package edu.nf.test.demo02;

import edu.nf.test.demo.ContainerFactory;

import java.lang.reflect.Field;

/**
 * @author CSY
 * @date 2025 - 04 - 16
 */
public class FieldInjectHandler {

    public void handle(Object instance, ContainerFactory containerFactory) {
        for (Field field : instance.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(Inject.class)) {
                String name = field.getAnnotation(Inject.class).value();
                Object instanceObj = containerFactory.getBean(name);
                setValue(field,instance,instanceObj);
            }
        }
    }

    private void setValue(Field field,Object instance,Object value) {

        try {
            if (!field.canAccess(instance)) {
                field.setAccessible(true);
            }
            field.set(instance,value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
